#
# openlookup/lib/sexp.py
#
# Copyright 2006-2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# This file derives from netstring.py and nson.py in pdis/messkit.

"""
Canonical S-expressions

Canonical s-expressions are an encoding for lists of strings and
nested lists (see http://theory.lcs.mit.edu/~rivest/sexp.html).
"""

#
# list -> canonical s-expression
#

def encode(list):
    """
    Encode a Python list as an s-expression.

    >>> encode(['red', ['blue', 'green']])
    '(3:red(4:blue5:green))'

    >>> encode('')
    Traceback (most recent call last):
        ...
    ValueError: Expected sequence, not string.
    >>> encode([])
    '()'
    >>> encode(())
    '()'
    >>> encode([''])
    '(0:)'
    >>> encode(['', 'a', u'xyz'])
    '(0:1:a3:xyz)'
    >>> encode([[[]]])
    '((()))'
    >>> encode(['', [], ['', []], [[], '']])
    '(0:()(0:())(()0:))'
    >>> encode(['xyz', [], ['xyz', []], [[], 'xyz']])
    '(3:xyz()(3:xyz())(()3:xyz))'
    """
    if isinstance(list, (str, unicode, buffer)):
        raise ValueError('Expected sequence, not string.')
    else:
        return ''.join(_encode_list(list))

def _encode(x):
    if isinstance(x, unicode):
        x = x.encode('utf-8')

    if isinstance(x, str):
        return [str(len(x)), ':', x]
    else:
        return _encode_list(x)

def _encode_list(x):
    buf = ['(']
    for v in x:
        buf.extend(_encode(v))
    return buf + [')']

#
# canonical s-expression -> list
#

def decode(string):
    """
    Decode an s-expression as a Python list.

    >>> decode('(3:red(4:blue5:green))')
    ['red', ['blue', 'green']]

    >>> decode('() ')
    Traceback (most recent call last):
        ...
    ValueError
    """
    list, k = parse_list(string)
    if k == len(string):
        return list
    else:
        raise ValueError

def parse_string(string, start=0):
    """
    Decode an atom ("<len>:<value>") starting at the given index.

    The return value is a tuple (s, k), where s is the decoded string
    and k is the total number of bytes in the undecoded string.  If
    the atom is invalid or the end of the input string is reached
    before the end of the atom is seen, ValueError is raised.

    >>> parse_string('3:redmond')
    ('red', 5)
    >>> parse_string('0:')
    ('', 2)
    >>> parse_string('2:x')
    Traceback (most recent call last):
        ...
    ValueError
    >>> parse_string('')
    Traceback (most recent call last):
        ...
    ValueError: substring not found
    >>> parse_string(':')
    Traceback (most recent call last):
        ...
    ValueError
    >>> parse_string(' 0:')
    Traceback (most recent call last):
        ...
    ValueError
    >>> parse_string('-0:')
    Traceback (most recent call last):
        ...
    ValueError
    >>> parse_string('00:')
    Traceback (most recent call last):
        ...
    ValueError
    """
    colon = string.index(':', start)
    head = string[start:colon]
    if not head.isdigit() or head[0] == '0' and head != '0':
        raise ValueError

    n = int(head)
    end = colon + n + 1
    if len(string) < end:
        raise ValueError

    return string[colon + 1: end], end - start

def parse_list(string, start=0):
    """
    Decode an s-expression starting at the given index.

    The return value is a tuple (x, k), where x is a Python list and k
    is the total number of bytes in the undecoded s-expression.  If
    the s-expression is invalid or the end of the input string is
    reached before the end of the s-expression is seen, ValueError
    is raised.

    >>> parse_list('()')
    ([], 2)
    >>> parse_list(' () ', 1)
    ([], 2)
    >>> parse_list('(0:)')
    ([''], 4)
    >>> parse_list('(())')
    ([[]], 4)
    >>> parse_list('(2:())')
    (['()'], 6)

    >>> parse_list(' () ')
    Traceback (most recent call last):
        ...
    ValueError
    >>> parse_list('( )')
    Traceback (most recent call last):
        ...
    ValueError: substring not found
    >>> parse_list('(:)')
    Traceback (most recent call last):
        ...
    ValueError
    >>> parse_list('(2:)')
    Traceback (most recent call last):
        ...
    ValueError
    >>> parse_list('(1:)')
    Traceback (most recent call last):
        ...
    ValueError
    """
    result = []
    pos = start

    try:
        if string[pos] != '(':
            raise ValueError

        pos += 1                # '('

        while string[pos] != ')':
            if string[pos] == '(':
                x, k = parse_list(string, pos)
            else:
                x, k = parse_string(string, pos)

            result.append(x)
            pos += k

        pos += 1                # ')'

        return result, pos - start
    except IndexError:
        raise ValueError

if __name__ == '__main__':
    import doctest
    doctest.testmod()
